package com.akino.gulimall.product.web;

import com.akino.gulimall.product.entity.CategoryEntity;
import com.akino.gulimall.product.service.CategoryService;
import com.akino.gulimall.product.vo.Catelog2Vo;
import com.alibaba.fastjson.JSON;
import org.redisson.api.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Akino
 * @version 1.0
 */
@Controller
public class IndexController {
    @Autowired
    CategoryService categoryService;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    StringRedisTemplate redisTemplate;
    @GetMapping({"/","/index.html"})
//    @GetMapping("/")
    public String indexPage(Model model){
        // TODO 1.查出所有一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categories();
        System.out.println("查出所有一级分类...");
        model.addAttribute("categorys",categoryEntities);
        return "index";
    }

    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson(){
        Map<String, List<Catelog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        // 1.获取一把锁，只要锁的名字一样，就是同一把锁
        RLock lock = redissonClient.getLock("my-lock");
        // 2.加锁
//        lock.lock();  // 阻塞式等待
        lock.lock(10, TimeUnit.SECONDS); // 10秒自动解锁（自动解锁时间一定要大于业务执行时间）
//        lock.lock(10, TimeUnit.SECONDS); 锁时间到了之后不会自动续期
        // 原理：如果传递了传递了锁的超时时间，就发送给redis执行脚本，进行占锁，默认超时就是指定的时间
        //      如果没有传递锁的超时时间，就使用看门狗的默认时间（30秒）
        //          只要占锁成功，就会启动一个定时任务，重新给锁设置过期时间，新的过期时间就是看门狗的默认时间
        //
        try{
            System.out.println("加锁成功，执行业务..."+Thread.currentThread().getId());
            Thread.sleep(30000);
        }catch (Exception e){

        }finally {
            // 3.解锁
            System.out.println("释放锁..."+Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }

    /**
     * -读写锁：改数据加写锁，读数据加读锁
     * @return
     */
    @ResponseBody
    @GetMapping("/write")
    public String writeValue(){  // 写业务
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = lock.writeLock();
        rLock.lock();
        try {
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            redisTemplate.opsForValue().set("writeValue",s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return s;
    }
    @ResponseBody
    @GetMapping("/read")
    public String readValue(){  // 读数据
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock");
        String writeValue = "";
        RLock rLock = lock.readLock();
        rLock.lock();
        try {
            writeValue = redisTemplate.opsForValue().get("writeValue");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return writeValue;
    }
    /**
     * -信号量
     * 模拟：车库停车，车库里只有三个车位
     */
    @ResponseBody
    @GetMapping("/park")
    public String park() throws Exception{  // 停车
        RSemaphore park = redissonClient.getSemaphore("park");
//            park.acquire();  // 获取一个信号（占一个车位）
            boolean b = park.tryAcquire();
        return "ok"+b;
    }
    @ResponseBody
    @GetMapping("/go")
    public String go(){  // 开车走
        RSemaphore park = redissonClient.getSemaphore("park");
        park.release();  // 释放一个车位
        return "ok";
    }
    /**
     * -闭锁
     * 放假，锁门
     * 5个班全部走完，锁大门
     */
    @ResponseBody
    @GetMapping("/lockDoor")
    public String lockDoor() throws InterruptedException { // 关大门
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();  // 等待闭锁都完成
        return "放假了...";
    }
    @ResponseBody
    @GetMapping("/gogogo/{id}")
    public String gogogo(@PathVariable("id") Long id){
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.countDown();  // 计数-1
        return id+"班的人都走了...";
    }
}
